package com.izobnehc.rabbit.rabbitadmin.controller;

import com.izobnehc.rabbit.rabbitadmin.domain.User;
import com.izobnehc.rabbit.rabbitadmin.service.UserService;
import com.izobnehc.rabbit.rabbitframework.common.domain.PageInfo;
import com.izobnehc.rabbit.rabbitframework.common.domain.PageResult;
import com.izobnehc.rabbit.rabbitframework.common.domain.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import java.util.List;

/**
* @author 11272
* @date 2023-10-16 17:02:15
*/
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 通过id获取元素
     */
    @GetMapping("/{userId}")
    public Result<User> get(@PathVariable String userId) {
        User user = userService.getById(userId);
        return Result.success(user);
    }

    /**
     * 获取列表全部
     */
    @GetMapping
    public Result<List<User>> list() {
        List<User> list = userService.list();
        return Result.success(list);
    }

    /**
     * 添加元素(无需主键)
     */
    @PostMapping
    public Result<Boolean> save(@RequestBody User user) {

        boolean result = userService.saveOrUpdate(user);
        return Result.success(result);
    }

    /**
     * 修改元素(需要主键)
     */
    @PutMapping
    public Result<Boolean> update(@RequestBody User user) {

        boolean result = userService.saveOrUpdate(user);
        return Result.success(result);
    }

    /**
     * 通过id删除元素
     */
    @DeleteMapping("/{userId}")
    public Result<Boolean> delete(@PathVariable String userId) {
        boolean result = userService.removeById(userId);
        return Result.success(result);
    }

    /**
    * 分页查询
    *
    * @param pageNum  当前页
    * @param pageSize 单页大小
    */
    @GetMapping("/{pageNum}/{pageSize}")
    public PageResult<List<User>> page(@PathVariable("pageNum") Integer pageNum, @PathVariable("pageSize") Integer pageSize) {

        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.orderBy(true, false, "sort");

        IPage<User> iPage = userService.page(new Page<>(pageNum, pageSize), wrapper);

        PageInfo pageInfo = new PageInfo(iPage.getCurrent(), iPage.getSize(), iPage.getTotal(), iPage.getPages());

        return new PageResult<>(Result.success(iPage.getRecords()), pageInfo);
    }

}
